package com.autonavi.yunda.yunji.common.web;

import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ruirui.cr@alibaba-inc.com
 * @date 2022/8/297:39 PM
 */
@Slf4j
public class YunjiCorsFilter implements Filter {

    public YunjiCorsFilter(){

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        String origin = req.getHeader("Origin");

        HttpServletResponse res = (HttpServletResponse) response;
        if(!Strings.isBlank(origin)){
            res.addHeader("Access-Control-Allow-Origin", origin);
        }else{
            res.addHeader("Access-Control-Allow-Origin", "*");
        }
        res.addHeader("Access-Control-Allow-Credentials", "true");
        res.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");

        //StringBuilder sb = new StringBuilder();
        //Iterator<String> headerIterator = req.getHeaderNames().asIterator();
        //while (headerIterator.hasNext()){
        //    sb.append(headerIterator.next());
        //    if(headerIterator.hasNext()){
        //        sb.append(",");
        //    }
        //}
        //res.addHeader("Access-Control-Allow-Headers", sb.toString());
        res.addHeader("Access-Control-Allow-Headers", "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Length,Authorization,Accept,key,x-biz,x-info,platinfo,gzipped");

        if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
            response.getWriter().println("ok");
            return;
        }
        log.debug("[YunjiCorsFilter] Add CORS header for req: {}", req.getRemoteAddr());
        chain.doFilter(request, response);
    }
}
